package com.agmte.api.config.filter;

import com.agmte.api.component.response.CustomApiResult;
import com.agmte.api.config.knife4.Knife4jApiConfiguration;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.net.URLDecoder;

@RestControllerAdvice
public class Knife4ApiAdvice implements ResponseBodyAdvice<Object> {


    @Resource
    private Knife4ApiScanner scanner;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(body instanceof CustomApiResult) {
            return body;
        }

        String path = request.getURI().getPath();
        String uri = URLDecoder.decode(request.getURI().toString());
        // 判断请求路径是否是/v2/api-docs
        if (path.contains("/v2/api-docs") && uri.contains(Knife4jApiConfiguration.groupName)) {
            // 这里是接口文档的请求，可以做特殊处理
            // 例如直接返回原始body，不包装等
            Json json = (Json) body;
            String value = json.value();

            JSONObject all = JSONObject.parseObject(value);

            all.getJSONObject("definitions").putAll(Knife4ApiScanner.modelMap);

            all.getJSONArray("tags").addAll(Knife4ApiScanner.tags);

            all.getJSONObject("paths").putAll(Knife4ApiScanner.paths);


            json = new Json(all.toJSONString());
            return json;
        }

        return body;
    }
}